package com.cqhilink.api.common.utils.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域过滤器
 *
 * @author 王镇
 * @create 2017-02-27 14:45
 * Access-Control-Allow-Origin: 允许跨域访问的域，可以是一个域的列表，也可以是通配符"*"。这里要注意Origin规则只对域名有效，并不会对子目录有效。即http://foo.example/subdir/ 是无效的。但是不同子域名需要分开设置，这里的规则可以参照同源策略
 * Access-Control-Allow-Credentials: 是否允许请求带有验证信息，
 * Access-Control-Expose-Headers: 允许脚本访问的返回头，请求成功后，脚本可以在
 * Access-Control-Max-Age: 缓存此次请求的秒数。在这个时间范围内，所有同类型的请求都将不再发送预检请求而是直接使用此次返回的头作为判断依据，非常有用，大幅优化请求次数
 * Access-Control-Allow-Methods: 允许使用的请求方法，以逗号隔开
 * Access-Control-Allow-Headers: 允许自定义的头部，以逗号隔开，大小写不敏感
 * 将Access-Control-Allow-Origin设置为：Access-Control-Allow-Origin: * 允许任何来自任意域的跨域请求，那么久存在被 DDoS攻击的可能
 */
public class CrossOriginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 跨域的设置
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if (httpRequest.getHeader("Origin") != null){
            if(httpRequest.getHeader("Origin").contains("192.168.0")) {
                // 指定允许其他域名访问
                httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("Origin"));
            }
        }

        // 响应类型
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        // 缓存 CORS 配置的时间
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        // 响应头设置
        httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization");
        // 是否允许请求带有验证信息
        httpResponse.setHeader("Access-Control-Allow-Credentials","true");
        // 响应文件类型
        httpResponse.setCharacterEncoding("utf-8");

          // 简单方式
//        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
//        httpResponse.setHeader("Access-Control-Allow-Methods", "GET");
//        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,zyqToken");

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
